import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/api/http_server/file_collection.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/master/file_info_list.dart';
import 'package:loxen/mode/master/file_loxen.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';

class FileInfoViewModel extends BaseViewModel with FileCollectionMixin {
  bool _isDelete = false;

  bool get isDelete => _isDelete;

  set isDelete(bool value) {
    _isDelete = value;
    notifyListeners();
  }

  final String userId;
  final FileLoxen fileLoxen;
  final FileType type;

  FileInfoViewModel(this.fileLoxen, this.type, this.userId);

  FileInfoList _bean;
  List<FileInfo> _list;
  int page = 1;

  List<FileInfo> get list => _list;

  void deleteData({Function(String msg) onError}) {
    String ids;
    var list = _list.where((element) => element.select == 1);
    if (list.length > 0) {
      ids = list.map((e) => e.id.toString()).toList().join("_");
    }
    if (ids != null && ids.trim() != '') {
      getDeleteResponse(ids).listen((event) {
        if (event == 200) {
          _list = _list.where((element) => element.select == 0).toList();
          fileLoxen.num = _list.length;
          notifyListeners();
        } else {
          if (onError != null) onError.call('删除失败');
        }
      }, onError: (error, stack) {
        if (onError != null) onError.call('网络异常');
        print("error   $error");
        print("stack   $stack");
      });
    }
  }

  void unSelectAll() {
    if (_list == null) return;
    _list.forEach((element) => element.select = 0);
    notifyListeners();
  }

  void selectAll() {
    if (_list == null) return;
    _list.forEach((element) => element.select = 1);
    notifyListeners();
  }

  void selectEntity(FileInfo fileInfo) {
    if (fileInfo.select == 1) {
      fileInfo.select = 0;
    } else {
      fileInfo.select = 1;
    }
    notifyListeners();
  }

  void nextData() {
    print('下一页');
    if (_bean.next == '') return;
    page += 1;
    nextInspiration();
  }

  void loadData() {
    getDataResponse()
        .doOnListen(() {
          mState = BaseState.LOADING;
          notifyListeners();
        })
        .flatMap((value) => compute(decodeFileInfoBean, value.data).asStream())
        .listen((event) {
          if (event.data != null && event.data.count > 0) {
            print('我的学习');
            print(event.data);
            _bean = event.data;
            _list = _bean.results;
            mState = BaseState.CONTENT;
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error, stack) {
          mState = BaseState.FAIL;
          print(error);
          print(stack);
        }, onDone: () => notifyListeners());
  }

  void nextInspiration() {
    getDataResponse()
        .flatMap((value) => compute(decodeFileInfoBean, value.data).asStream())
        .listen((event) {
      if (event.data != null) {
        _bean = event.data;
        List<FileInfo> list = [];
        list.addAll(_list);
        list.addAll(event.data.results);
        _list = list;
        notifyListeners();
      }
    }, onError: (error, stack) {
      print(error);
      print(stack);
    });
  }

  Stream<int> getDeleteResponse(String ids) {
    if (type == FileType.INSPIRATION) {
      return deleteCollection(
          ids, ContentType.IDEA_ARTICLE, fileLoxen.id.toString());
    } else if (type == FileType.MATERIAL) {
      return deleteCollection(
          ids, ContentType.MATERIAL_PRODUCT, fileLoxen.id.toString());
    } else {
      return deleteCollection(
          ids, ContentType.IDEA_PICTURE, fileLoxen.id.toString());
    }
  }

  Stream<Response> getDataResponse() {
    if (type == FileType.INSPIRATION) {
      return ApiService.fileInfo(fileLoxen.id.toString(), ContentType.IDEA_ARTICLE,
          page: page.toString(), userId: userId);
    } else if (type == FileType.MATERIAL) {
      return ApiService.fileInfo(fileLoxen.id.toString(), ContentType.MATERIAL_PRODUCT,
          page: page.toString(), userId: userId);
    } else {
      return ApiService.fileInfo(fileLoxen.id.toString(), ContentType.IDEA_PICTURE,
          page: page.toString(), userId: userId);
    }
  }

  static BaseMode<FileInfoList> decodeFileInfoBean(dynamic json) {
    return BaseMode<FileInfoList>(json);
  }
}
